import React, {useEffect, useState} from 'react';
import {
    Button,
    Card,
    Col,
    Drawer,
    Form,
    Input,
    message,
    Modal,
    Row,
    Select,
    Space,
    Table,
    Tag
} from 'antd';
import {DeleteOutlined, EditOutlined, PlusOutlined, ReloadOutlined, SearchOutlined} from '@ant-design/icons';
import {addProject, deleteProject, getByProjectId, getListProjectByPage, updateProject} from "@/api/project";
import {getListTemplate} from "@/api/template";
import {statusEnum} from "@/model/enum";
import {differenceBy} from 'lodash';
import {ProjectType} from "@/pages/project/type";

const Index: React.FC = () => {
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [form] = Form.useForm<ProjectType>();
    const [originData, setOriginData] = useState(null);
    const [data, setData] = useState<[]>([]);
    const [editingKey, setEditingKey] = useState<number | null>(null);
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showTotal: (total: number) => `共 ${total} 条`
    });

    // 添加搜索表单
    const [searchForm] = Form.useForm();
    const [drawerOpen, setDrawerOpen] = useState(false);

    const [selectTemplate, setSelectTemplate] = useState<[]>([]);

    // 获取列表数据
    const fetchData = async (params: { current: number; pageSize: number; bookName?: string; author?: string }) => {
        setLoading(true);
        try {
            const response = await getListProjectByPage(params);
            if (response.code === 0) {
                setData(response.data.records);
                setPagination({
                    ...pagination,
                    current: params.current,
                    pageSize: params.pageSize,
                    total: response.data.total
                });
            } else {
                message.error(response.message || '获取数据失败');
            }
        } catch (error) {
            message.error('获取数据失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData({
            current: 1,
            pageSize: 10
        });
    }, []);

    const columns = [
        {
            title: '代码',
            dataIndex: 'code',
            key: 'code',
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
        },
        {
            title: '排序',
            dataIndex: 'sortable',
            key: 'sortable',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status: number) => {
                switch (status) {
                    case 0:
                        return <Tag color="red">禁用</Tag>;
                    case 1:
                        return <Tag color="blue">启用</Tag>;
                    case 2:
                        return <Tag color="green">备份</Tag>;
                    default:
                        return <Tag color="blue">未知</Tag>;
                }
            },
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (text: string) => new Date(text).toLocaleString(),
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render: (text: string) => new Date(text).toLocaleString(),
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EditOutlined/>}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined/>}
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    /**
     * 获取模板数据
     */
    const fetchTemplate = async () => {
        try {
            const response = await getListTemplate({});
            const res = response.data.map((item) => {
                return {
                    value: item.id,
                    label: item.code + ' | ' + item.description
                }
            });
            setSelectTemplate(res)
        }catch (e){
            message.error('获取模板数据失败');
        }
    }

    const handleAdd = async () => {
        form.resetFields();
        setEditingKey(null);
        setDrawerOpen(true);
        await fetchTemplate()
    };

    const handleEdit = async (record) => {
        await fetchTemplate()
        try {
            setEditingKey(record.id);
            const res = await getByProjectId(record.id);
            setOriginData(res.data);
            form.setFieldsValue(res.data);
            setDrawerOpen(true);
        } catch (error) {
            message.error('获取项目数据失败');
        }
    };

    const handleDelete = (id: number) => {
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除这条数据？',
            onOk: async () => {
                try {
                    await deleteProject({id: id});
                    message.success('删除成功');
                    if (data.length === 1 && pagination.current > 1) {
                        await fetchData({
                            current: pagination.current - 1,
                            pageSize: pagination.pageSize
                        });
                    } else {
                        await fetchData({
                            current: pagination.current,
                            pageSize: pagination.pageSize
                        });
                    }
                } catch (error) {
                    message.error('删除失败');
                }
            },
        });
    };

    const handleModalOk = async () => {
        try {
            // const values = await form.validateFields();
            const values = await form.validateFields() as ProjectType;
            const currentTemplateIds = Array.isArray(values.templateIds) ? values.templateIds : [];
            const originalTemplateIds = Array.isArray(originData?.templateIds) ? originData.templateIds : [];
            if (editingKey) {
                // 和原来的绑定模板数据作比较
                const addTemplate = differenceBy(currentTemplateIds, originalTemplateIds)
                const deleteTemplate = differenceBy(originalTemplateIds, currentTemplateIds)
                const response = await updateProject({
                    ...values,
                    id: editingKey,
                    addTemplate: addTemplate,
                    deleteTemplate: deleteTemplate,
                });
                if (response.code === 0) {
                    message.success('更新成功');
                    setDrawerOpen(false);
                    await fetchData({
                        current: pagination.current,
                        pageSize: pagination.pageSize
                    });
                } else {
                    message.error(response.message || '更新失败');
                }
            } else {
                const response = await addProject(values);
                if (response.code === 0) {
                    message.success('添加成功');
                    setDrawerOpen(false);
                    await fetchData({
                        current: 1,
                        pageSize: pagination.pageSize
                    });
                } else {
                    message.error(response.message || '添加失败');
                }
            }
        } catch (error) {
            message.error('操作失败');
        }
    };

    // 处理搜索
    const handleSearch = async () => {
        const values = await searchForm.validateFields();
        await fetchData({
            ...values,
            current: 1,
            pageSize: pagination.pageSize
        });
    };

    // 重置搜索
    const handleReset = () => {
        searchForm.resetFields();
        fetchData({
            current: 1,
            pageSize: pagination.pageSize
        });
    };

    // 修改表格变化处理函数，保留搜索条件
    const handleTableChange = (newPagination: any) => {
        const values = searchForm.getFieldsValue();
        fetchData({
            ...values,
            current: newPagination.current,
            pageSize: newPagination.pageSize
        });
    };

    const onClose = () => {
        setDrawerOpen(false);
    };

    return (
        <div>
            <Card>
                <Form
                    form={searchForm}
                    layout="inline"
                    style={{marginBottom: 16}}
                >
                    <Row gutter={16} style={{width: '100%'}}>
                        <Col span={6}>
                            <Form.Item>
                                <Input placeholder="请输入代码" allowClear/>
                            </Form.Item>
                        </Col>
                        <Col span={12} style={{textAlign: 'right'}}>
                            <Space>
                                <Button
                                    type="primary"
                                    icon={<SearchOutlined/>}
                                    onClick={handleSearch}
                                >
                                    搜索
                                </Button>
                                <Button
                                    icon={<ReloadOutlined/>}
                                    onClick={handleReset}
                                >
                                    重置
                                </Button>
                                <Button
                                    type="primary"
                                    icon={<PlusOutlined/>}
                                    onClick={handleAdd}
                                >
                                    添加
                                </Button>
                            </Space>
                        </Col>
                    </Row>
                </Form>

                <Table
                    columns={columns}
                    dataSource={data}
                    rowKey="id"
                    pagination={pagination}
                    loading={loading}
                    onChange={handleTableChange}
                />
            </Card>

            <Drawer
                title={`代码模板`}
                placement="right"
                width={'60vw'}
                onClose={onClose}
                open={drawerOpen}
                extra={
                    <Space>
                        <Button onClick={onClose}>取消</Button>
                        <Button type="primary" onClick={handleModalOk}>
                            确认
                        </Button>
                    </Space>
                }
            >
                <Form form={form}>
                    <Form.Item label="代码" name="code">
                        <Input/>
                    </Form.Item>
                    <Form.Item label="名称" name="name">
                        <Input/>
                    </Form.Item>
                    <Form.Item label="描述" name="description">
                        <Input/>
                    </Form.Item>
                    <Form.Item label="排序" name="sortable">
                        <Input/>
                    </Form.Item>
                    <Form.Item label="状态" name="status">
                        <Select options={statusEnum}/>
                    </Form.Item>
                    <Form.Item label="对应模板" name="templateIds">
                        <Select mode="multiple" showSearch options={selectTemplate} />
                    </Form.Item>
                </Form>
            </Drawer>
        </div>
    );
};

export default Index;